"""
    Handles 'user preferences'
    
    @author: Jean-Lou Dupont
"""
import logging
import uuid
import pickle

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import memcache

__all__ = ['UserPrefs']

class UserPrefs(db.Expando):
    """
        The base fields are:
        
        - user
        - uid
    """
    user = db.UserProperty(required=True)
    uid  = db.StringProperty()
    
    @staticmethod
    def create( u ):
        cached = UserPrefs.getFromCache( u )
        if (cached is not None):
            return cached
        
        query = db.Query( UserPrefs )
        #logging.info("UserPrefs.create  user[%s]" % str(user) )
        query.filter('user = ', u )
        try:
            result = query.fetch(limit=1)
        except:
            return UserPrefs.createNew(u)
        
        if result:
            if ( len(result) == 1 ):
                up = result[0]
                
            if not up.uid:
                up.uid = str( uuid.uuid1() )
                up.put()
                
            up.saveInCache()
            return up
        
        return UserPrefs.createNew(u)
    
    @staticmethod
    def createNew( u ):
        up = UserPrefs(user=u)
        up.uid = str( uuid.uuid1() )
        up.put()
        up.saveInCache()
        return up
        
    @staticmethod
    def fromUid( uid ):
        query = db.Query( UserPrefs )
        query.filter( 'uid = ', uid )
        try:
            result = query.fetch(limit=1)
        except:
            result = None
            
        if result:
            return result[0]
        
        return None

    @staticmethod
    def getFromCache(user):
        pickled = memcache.get('user/prefs/' + str( user ) )
        if (pickled is not None):
            prefs = pickle.loads(pickled)
            if (prefs is not None):
                return prefs
        return None

    def saveInCache(self, timeout = 600):
        pickled = pickle.dumps( self )
        result = memcache.set('user/prefs/' + str( self.user ), pickled, timeout )
        #logging.info( "UserPrefs.saveInCache: user[%s] result[%i]" % ( str(self.user), result ) )
